package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"

	"gitee.com/daonna/video-copyright-blockchain/config"
	"gitee.com/daonna/video-copyright-blockchain/internal/handlers"
	"gitee.com/daonna/video-copyright-blockchain/internal/services"
)

func main() {
	// 加载配置
	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}

	// 设置日志
	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	// 初始化服务
	videoService := services.NewVideoService()

	// 创建 Gin 引擎
	r := gin.Default()

	// 注册路由
	handlers.RegisterRoutes(r, videoService)

	// 创建 HTTP 服务器
	srv := &http.Server{
		Addr:    cfg.Server.Addr,
		Handler: r,
	}

	// 在一个单独的 goroutine 中启动服务器
	go func() {
		log.Printf("Starting server on %s", cfg.Server.Addr)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Failed to start server: %v", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")

	// 设置 5 秒的超时时间来关闭服务器
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}

	log.Println("Server exiting")
}
